﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.DrawingCore;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Company.Project.Infrastructure.Utility.BaseEnums;
using Company.Utility.CustomerAttribute;
using Company.Utility.Encrypt;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace Company.Utility
{
    public class Common
    {
        public Common()
        {
            
        }
        // 从完整路径中,分解出目录
        public static string ExtractFilePath(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            char[] arrF = fullpath.Trim().ToCharArray();
            int ipos = -1;
            for (int i = arrF.Length - 1; i >= 0; i--)
            {
                if (arrF[i] == '\\')
                {
                    break;
                }
                else
                {
                    ipos = i;
                }
            }

            if (ipos == -1)
            {
                return "";
            }

            StringBuilder strB = new StringBuilder();
            for (int i = 0; i < ipos; i++)
            {
                strB.Append(arrF[i]);
            }
            return strB.ToString();
        }

        // 分隔出上级目录
        public static string ExtractPathParent(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            if (fullpath[fullpath.Length - 1] == '\\')
            {
                fullpath = fullpath.Substring(0, fullpath.Length - 1);
            }
            return Common.ExtractFilePath(fullpath);
        }

        // 从完整路径中分离出文件名称
        public static string ExtractFileName(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            char[] arrF = fullpath.Trim().ToCharArray();
            int ipos = -1;
            for (int i = arrF.Length - 1; i >= 0; i--)
            {
                if (arrF[i] == '\\')
                {
                    break;
                }
                else
                {
                    ipos = i;
                }
            }

            if (ipos == -1)
            {
                return "";
            }

            StringBuilder strB = new StringBuilder();
            for (int i = ipos; i < arrF.Length; i++)
            {
                strB.Append(arrF[i]);
            }
            return strB.ToString();
        }

        // 从文件名中分离出扩展名
        public static string ExtractFileExt(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            char[] arrF = fullpath.Trim().ToCharArray();
            int ipos = -1;
            for (int i = arrF.Length - 1; i >= 0; i--)
            {
                if (arrF[i] == '\\' || arrF[i] == '.')
                {
                    if (arrF[i] == '.')
                    {
                        ipos = i;
                    }
                    break;
                }
                else
                {
                    ipos = i;
                }
            }

            if (ipos == -1)
            {
                return "";
            }

            StringBuilder strB = new StringBuilder();
            for (int i = ipos; i < arrF.Length; i++)
            {
                strB.Append(arrF[i]);
            }
            return strB.ToString();
        }

        // 判断当前路径是否为目录
        public static bool checkIsPath(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return false;
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return false;
            }

            return fullpath[fullpath.Length - 1] == '\\';
        }

        // 判断当前路径是否为文件名
        public static bool checkIsFilename(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return false;
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return false;
            }

            return fullpath[fullpath.Length - 1] != '\\';
        }
        // 获取主文件名
        public static string ExtractFileMain(string fullpath)
        {
            if (Common.checkIsPath(fullpath))
            {// 是目录
                return "";
            }
            else if (!Common.checkIsFilename(fullpath))
            {
                return "";
            }

            string sFileName = Common.ExtractFileName(fullpath);
            if (String.IsNullOrEmpty(sFileName))
            {
                return "";
            }

            string sExt = Common.ExtractFileExt(fullpath);
            if (String.IsNullOrEmpty(sExt))
            {
                return sFileName;
            }

            return Common.ExtractFilePath(fullpath) + TString.leftStr(sFileName, sFileName.Length - sExt.Length);
        }

        // 处理目录中的反斜线
        public static string repairPath(string fullpath)
        {
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            fullpath = fullpath.Trim();
            if (String.IsNullOrEmpty(fullpath))
            {
                return "";
            }

            StringBuilder result = new StringBuilder();
            string[] arrF = fullpath.Split('\\');
            for (int i = 0; i < arrF.Length; i++)
            {
                string sline = arrF[i];
                if (String.IsNullOrEmpty(sline))
                {
                    continue;
                }
                else if (String.IsNullOrEmpty(sline.Trim()))
                {
                    continue;
                }
                else
                {
                    result.Append(sline.Trim());
                    result.Append('\\');
                }
            }
            return result.ToString();
        }

        // 处理文件名中的反斜线
        public static string repairFileName(string filename)
        {
            if (String.IsNullOrEmpty(filename))
            {
                return "";
            }

            filename = filename.Trim();
            if (String.IsNullOrEmpty(filename))
            {
                return "";
            }

            StringBuilder result = new StringBuilder();
            string[] arrF = filename.Split('\\');
            for (int i = 0; i < arrF.Length; i++)
            {
                string sline = arrF[i];
                if (String.IsNullOrEmpty(sline))
                {
                    continue;
                }
                else if (String.IsNullOrEmpty(sline.Trim()))
                {
                    continue;
                }
                else
                {
                    if (result.Length > 0)
                    {
                        result.Append('\\');
                    }
                    result.Append(sline.Trim());
                }
            }
            return result.ToString();
        }

        /// <summary>
        /// 生成固定长度数字串
        /// </summary>
        /// <param name="iLen">长度</param>
        /// <returns></returns>
        public static string GetRandom(int iLen)
        {
            string sResult = String.Empty;
            Random rd = new Random(Guid.NewGuid().GetHashCode());
            switch (iLen)
            {
                case 1:
                    sResult = rd.Next(0, 9).ToString();
                    break;
                case 2:
                    sResult = rd.Next(10, 99).ToString();
                    break;
                case 3:
                    sResult = rd.Next(100, 999).ToString();
                    break;
                case 4:
                    sResult = rd.Next(1000, 9999).ToString();
                    break;
                case 5:
                    sResult = rd.Next(10000, 99999).ToString();
                    break;
                case 6:
                    sResult = rd.Next(100000, 999999).ToString();
                    break;
            }
            return sResult;
        }

        public static string GetRandomCode(int iLen)
        {
            string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var newChar = "";
            for (int i = 0; i < iLen; i++)
            {
                var rd = new Random(Guid.NewGuid().GetHashCode());
                var rdc = rd.Next(0, chars.Length - 1);
                newChar += chars.Substring(rdc, 1);
            }
            return newChar;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            #region md5加密
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = Encoding.UTF8.GetBytes(str);
            byte[] md5data = md5.ComputeHash(data);
            md5.Clear();
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < md5data.Length; i++)
            {
                sBuilder.Append(md5data[i].ToString("X2"));
            }
            return sBuilder.ToString();
            #endregion
        }
        public static string setSucc(bool bResult, string sMessage)
        {
            if (bResult)
                return "{\"success\":true,\"message\":\"" + sMessage + "\"}";
            else
                return "{\"success\":false,\"message\":\"" + sMessage + "\"}";
        }

        public static string ToJsonString(object item)
        {
            return JsonConvert.SerializeObject(item, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
        }

        public static JToken ItemToJson(object item)
        {
            try
            {
                return (JToken)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(item, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
            }
            catch (Exception)
            {
                // ignored
            }
            return null;
        }

        /// <summary>
        /// 时间格式为（年月日）
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static JToken ItemToJsonYMD(object item)
        {
            return (JToken)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(item, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" }));

        }

        /// <summary>
        /// 根据id生成编号
        /// </summary>
        /// <param name="iId"></param>
        /// <returns></returns>
        public static string IDtoNO(long iId)
        {
            string sResult = String.Empty;
            string sId = TConvert.toString(iId);
            while (sId.Length < 6)
            {
                sId = sId.Insert(0, "0");
            }
            return sId;
        }
        //static readonly string sMsgAccount = System.Configuration.ConfigurationManager.AppSettings["account"].ToString();
        //static readonly string sMsgPassword = System.Configuration.ConfigurationManager.AppSettings["password"].ToString();
        //static readonly string sMsgMD5key = System.Configuration.ConfigurationManager.AppSettings["MD5key"].ToString();

        ///// <summary>
        ///// 发送短信
        ///// </summary>
        ///// <param name="sMobile">手机号 多个号码 请用英文逗号隔开</param>
        ///// <param name="sMsg">短信内容</param>
        ///// <returns></returns>
        //public static bool SendPhoneMsg(string sMobile, string sMsg)
        //{
        //    bool bResult = false;

        //    string sContent = System.Web.HttpUtility.UrlEncode(Encoding.GetEncoding("UTF-8").GetBytes(sMsg));
        //    StringBuilder sUrl = new StringBuilder();
        //    sUrl.Append("http://sdk8.interface.sudas.cn/z_mdsmssend.php");
        //    sUrl.Append("?sn=" + sMsgAccount + "&pwd=" + Security.GetMD5Hash(sMsgPassword).ToUpper() + "&mobile=" + sMobile);
        //    sUrl.Append("&ext=&rrid=&stime=&MD5key=" + sMsgMD5key + "&scode=1&stype=1&ssafe=2&debug=0&ssl=2&Md5Sign=");
        //    sUrl.Append("&content=" + sContent);
        //    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sUrl.ToString());
        //    webRequest.Method = "GET";
        //    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
        //    int iResult = Convert.ToInt32(webResponse.StatusCode);
        //    if (iResult == 200)
        //        bResult = true;
        //    return bResult;
        //}


        public static void WriteCookie(string strName, string strValue)
        {
            HttpContext.Current.Response.Cookies.Append(strName, strValue);
        }
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            var expiresDate = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.Cookies.Append(strName, strValue, new CookieOptions() { Expires = expiresDate });
        }
        #region URL处理
        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpUtility.UrlDecode(str);
        }
        #endregion

        public static string GetCookie(string strName)
        {
            string val = "";
            HttpContext.Current.Request.Cookies.TryGetValue(strName, out val);
            return val;
        }

        //public static int SendSMS(string mobile, string smsContent, string smsKey, string smsPwd)
        //{
        //    try
        //    {
        //        Link.LinkWSSoap lk = new Link.LinkWSSoapClient();
        //        int result = lk.BatchSend(smsKey, smsPwd, mobile, smsContent, "", "");
        //        return result;
        //    }
        //    catch (Exception)
        //    {
        //        return -1;
        //    }
        //}
        /// <summary>
        /// 根据URL获取远程资源访问状态
        /// </summary>
        /// <param name="curl"></param>
        /// <returns></returns>
        private static int GetRemoteResourceStatus(string curl)
        {
            int num = 200;
            if (curl.IndexOf("http://") != 0)
            {
                return 500;
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(curl));
            ServicePointManager.Expect100Continue = false;
            try
            {
                ((HttpWebResponse)request.GetResponse()).Close();
            }
            catch (WebException exception)
            {
                if (exception.Status != WebExceptionStatus.ProtocolError)
                {
                    return num;
                }
                if (exception.Message.IndexOf("500 ", StringComparison.Ordinal) > 0)
                {
                    return 500;
                }
                if (exception.Message.IndexOf("401 ", StringComparison.Ordinal) > 0)
                {
                    return 401;
                }
                if (exception.Message.IndexOf("404", StringComparison.Ordinal) > 0)
                {
                    num = 404;
                }
            }
            return num;
        }
        public static bool ChkImage(string ext)
        {
            var imageext = new string[] { ".jpg", ".gif", ".png", ".bmp", ".jpeg" };
            return imageext.Contains(ext);
        }

        public static bool IsRealHttpImg(string url)
        {
            if (GetRemoteResourceStatus(url) == 200)
            {
                var len = url.LastIndexOf('.');
                var ext = url.Substring(len, url.Length - len);
                if (ChkImage(ext))
                {
                    return true;
                }
            }
            return false;
        }

        public static bool LoadHttpImg(string url, out byte[] Contents)
        {
            if (IsRealHttpImg(url))
            {
                var web = new WebClient();
                Contents = web.DownloadData(url);
                return true;
            }
            else
            {
                Contents = new byte[0];
                return false;
            }
        }
        /// <summary>
        /// 设置Json返回值
        /// </summary>
        /// <param name="state"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public static string SetJson(bool state, string info)
        {
            JObject job = new JObject();
            job.Add(new JProperty("success", state));
            job.Add(new JProperty("message", info));
            return job.ToString();
        }

        public static T GetDefaultValue<T>(T t)
        {
            var pInfo = ((T)t).GetType().GetProperties();
            foreach (var pi in pInfo)
            {
                if (pi.PropertyType == typeof(string))
                {
                    if (pi.GetValue(t) == null)
                        pi.SetValue(t, "");
                }
            }
            return t;
        }
        public static DateTime GetTimeToString(string span)
        {
            if (span.Length != 14)
            {
                throw new CustomException(Enum_ApiResultCode.TimeExpire.GetValueToInt(),
                    EnumHelper.GetLocalizedDescription(Enum_ApiResultCode.TimeExpire));
            }
            var timeStr = span.Substring(0, 4) + "-" + span.Substring(4, 2) + "-" + span.Substring(6, 2)
                          + " " + span.Substring(8, 2) + ":" + span.Substring(10, 2) + ":" + span.Substring(12, 2);
            var time = DateTime.MinValue;
            if (DateTime.TryParse(timeStr, out time))
            {
                return time;
            }
            else
            {
                throw new CustomException(Enum_ApiResultCode.TimeExpire.GetValueToInt(),
                    EnumHelper.GetLocalizedDescription(Enum_ApiResultCode.TimeExpire));
            }
        }
        /// <summary>
        /// 统计分析时，按照年月日进行日期拆分
        /// </summary>
        /// <param name="query"></param>
        /// <param name="minTime"></param>
        /// <param name="maxTime"></param>
        /// <returns></returns>
        public static List<dynamic> GetRange(List<DateTime> query, DateTime minTime, DateTime maxTime)
        {
            var result = new List<dynamic>();
            if (query.Any())
            {
                if ((maxTime - minTime).Days == 0)
                {
                    var index = "";
                    var getday = "";
                    for (; minTime.CompareTo(maxTime.AddHours(1)) < 0; minTime = minTime.AddHours(1))
                    {
                        if (index != minTime.ToString("yy.MM.dd"))
                        {
                            getday = "yy.MM.dd ";
                            index = minTime.ToString("yy.MM.dd");
                        }
                        dynamic obj = new ExpandoObject();
                        obj.Key = minTime.ToString(getday + "HH时");
                        getday = "";
                        obj.Value = query.Count(x => x.Hour == minTime.Hour && x.Day == minTime.Day);
                        result.Add(obj);
                    }
                }
                else if ((maxTime - minTime).Days <= 7)
                {
                    for (; minTime.Date.CompareTo(maxTime.Date.AddDays(1)) < 0; minTime = minTime.AddDays(1).Date)
                    {
                        dynamic obj = new ExpandoObject();
                        obj.Key = minTime.Date.ToString("yyyy年MM月dd日");
                        obj.Value = query.Count(x => x.Date == minTime.Date);
                        result.Add(obj);
                    }
                }
                else if ((maxTime - minTime).Days <= 28)
                {
                    int dayOfWeek = Convert.ToInt32(minTime.DayOfWeek);
                    int daydiff = (-1) * dayOfWeek + 1;
                    var min = minTime.AddDays(daydiff).Date < Convert.ToDateTime(minTime.ToString("yyyy-MM-01"))
                        ? Convert.ToDateTime(minTime.ToString("yyyy-MM-01"))
                        : minTime.AddDays(daydiff).Date;
                    var diff = -1;
                    for (; min.CompareTo(maxTime.Date.AddDays(1)) < 0; min = min.AddDays(1))
                    {
                        if (diff != TConvertDateTime.WeekOfMonth(min, 1))
                        {
                            diff = TConvertDateTime.WeekOfMonth(min, 1);
                            dynamic obj = new ExpandoObject();
                            obj.Key = min.ToString("yyyy年MM月第") + TConvertDateTime.WeekOfMonth(min, 1) + "周";
                            dayOfWeek = Convert.ToInt32(min.DayOfWeek);
                            daydiff = (-1) * dayOfWeek + 1;
                            int dayadd = 7 - dayOfWeek;
                            var _min = min.AddDays(daydiff);
                            var _max = min.AddDays(dayadd).Date.AddDays(1);
                            obj.Value = query.Count(x => x.Date >= _min && x.Date < _max);
                            result.Add(obj);
                        }
                    }
                }
                else if ((maxTime - minTime).Days <= 365)
                {
                    var diff = -1;
                    for (; minTime.Date.CompareTo(maxTime.Date.AddDays(1)) < 0; minTime = minTime.AddDays(1).Date)
                    {
                        if (diff != minTime.Date.Month)
                        {
                            diff = minTime.Date.Month;
                            dynamic obj = new ExpandoObject();
                            obj.Key = minTime.ToString("yyyy年MM月");
                            var min = Convert.ToDateTime(minTime.ToString("yyyy-MM") + "-01");
                            var max =
                                Convert.ToDateTime(minTime.ToString("yyyy-MM") + "-01").AddMonths(1);
                            obj.Value = query.Count(x => x.Date >= min && x.Date < max);
                            result.Add(obj);
                        }
                    }
                }
                else
                {
                    var diff = -1;
                    for (; minTime.Date.CompareTo(maxTime.Date.AddDays(1)) < 0; minTime = minTime.AddDays(1).Date)
                    {
                        if (diff != minTime.Date.Year)
                        {
                            diff = minTime.Date.Year;
                            dynamic obj = new ExpandoObject();
                            obj.Key = minTime.ToString("yyyy年");
                            var min = Convert.ToDateTime(minTime.ToString("yyyy-01") + "-01");
                            var max =
                                Convert.ToDateTime(minTime.ToString("yyyy-01") + "-01").AddYears(1);
                            obj.Value = query.Count(x => x.Date >= min && x.Date < max);
                            result.Add(obj);
                        }
                    }
                }
            }
            return result;
        }

        public static ImageInfo GetProxyImage(string Url)
        {
            using (var ms = new MemoryStream(new WebClient().DownloadData(Url)))
            {
                var img = new Bitmap(ms);
                return new ImageInfo()
                {
                    Width = img.Width,
                    Height = img.Height
                };
            }
        }
        #region 验证browser
        public static bool IsMobileBrowser()
        {
            // http://detectmobilebrowsers.com/ 2014.8.1版本  修改支持ipad访问

            string u = HttpContext.Current.Request.Headers["User-Agent"].ToString();
            if (string.IsNullOrWhiteSpace(u)) return true;
            Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|ad|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
            {
                return true;
            }
            return false;
        }

        public static bool IsWeChatBrowser()
        {

            /*手机微信访问
             * 
*浏览器HTTP_USER_AGENT信息，苹果与安卓手机都会包含 MicroMessenger 其他手机就不包含了！
*目前只能对安卓与苹果手机做到完美识别
*其他手机只能判断是否为手机访问
*下面是我的识别代码：*/

            var userAgent = HttpContext.Current.Request.Headers["User-Agent"].ToString();
            //            获取为空的原因就是因为手机的上网类型是cmwap而不是cmnet 需要把手机的上网设置为cmnet类型 不是看你上的什么网 
            //cmwap cmnet是gprs接入点 接入点不同 就不一样 
            //一般cmwap 费用低 但网速慢 cmnet快 但费用高 


            if (!string.IsNullOrEmpty(userAgent)) //未找到代理信息，先暂时不验证咯 杨剑 2013年10月22日 14:03:35
            {
                if (
                    !(userAgent.IndexOf("MicroMessenger") > -1 ||
                      (userAgent.IndexOf("Nokia") > -1 && userAgent.IndexOf("SymbianOS") > -1) ||
                      (userAgent.IndexOf("Windows Phone") > -1 && userAgent.IndexOf("IEMobile") > -1))
                )
                {
                    return false;
                }
            }

            //限制浏览访问 end

            return true;
        }
        #endregion

        #region SimpLoginUser

        public static dynamic ReadSimpleLoginUser()
        {
            return JsonConvert.DeserializeObject<dynamic>(HttpContext.Current.User.FindFirst(ClaimTypes.UserData).Value);
        }
        public static async Task LoginIn(string LoginName, Guid ID, string PassWord, string LoginIp)
        {
            var identity = new ClaimsIdentity("Forms");
            identity.AddClaim(new Claim(ClaimTypes.UserData,
                JsonConvert.SerializeObject(new {ID, LoginName, PassWord, LoginIp})));
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.Current.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
        public static async Task LoginOut()
        {
            await HttpContext.Current.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
        //public class LoginUserDTO
        //{
        //    /// <summary>
        //    /// 编号
        //    /// </summary>
        //    public Guid ID { get; set; }

        //    /// <summary>
        //    /// 登录名
        //    /// </summary>
        //    public string LoginName { get; set; }
        //    /// <summary>
        //    /// 昵称
        //    /// </summary>
        //    public string NickName { get; set; }

        //    /// <summary>
        //    /// 角色编号
        //    /// </summary>
        //    public Guid RoleId { get; set; }
        //    public string PassWord { get; set; }
        //    public List<RoleActionDTO> UserActionList { get; set; }

        //    public List<RoleAction_ModuleDTO> DefActionList { get; set; }
        //    public string Menu { get; set; }

        //    public string LoginIp { get; set; }
        //    public Enum_ManagerUserState State { get; set; }
        //    public bool IsDeleted { get; set; }
        //}
        #endregion

       
    }


    public class ImageInfo
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }

   
}
